// 角色管理API接口
import type { Role, RoleFormData } from '../types/role';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { roleData } from '../data/roleData';

// 角色API基础路径
const ROLE_API_BASE = `${getAPI_BASE_URL_SYNC()}/roles`;

// API请求参数接口
export interface GetRolesParams {
  page?: number;
  pageSize?: number;
  search?: string;
  status?: number;
}

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 角色列表响应格式
interface RoleListResponse {
  roles: Role[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 角色模拟API实现
const mockRoleApi = {
  async getRoles(params: GetRolesParams = {}): Promise<ApiResponse<Role[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, status } = params;
    
    // 过滤数据
    let filteredData = [...roleData];
    
    if (search) {
      filteredData = filteredData.filter(role => 
        role.name.toLowerCase().includes(search.toLowerCase()) ||
        role.description?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取角色列表成功'
    };
  },

  async createRole(roleData: RoleFormData): Promise<ApiResponse<Role>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newRole: Role = {
      id: Date.now(),
      name: roleData.name,
      description: roleData.description || '',
      permissions: roleData.permissions || [],
      status: 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    roleData.push(newRole);
    
    return {
      data: newRole,
      total: 1,
      success: true,
      message: '角色创建成功'
    };
  },

  async updateRole(roleId: number, roleData: Partial<RoleFormData>): Promise<ApiResponse<Role>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = roleData.findIndex(role => role.id === roleId);
    if (index === -1) {
      throw new Error('角色不存在');
    }
    
    roleData[index] = { ...roleData[index], ...roleData, updatedAt: new Date().toISOString() };
    
    return {
      data: roleData[index],
      total: 1,
      success: true,
      message: '角色信息更新成功'
    };
  },

  async deleteRole(roleId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = roleData.findIndex(role => role.id === roleId);
    if (index === -1) {
      throw new Error('角色不存在');
    }
    
    roleData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '角色删除成功'
    };
  },

  async toggleRoleStatus(roleId: number, status: number): Promise<ApiResponse<Role>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = roleData.findIndex(role => role.id === roleId);
    if (index === -1) {
      throw new Error('角色不存在');
    }
    
    roleData[index].status = status;
    roleData[index].updatedAt = new Date().toISOString();
    
    return {
      data: roleData[index],
      total: 1,
      success: true,
      message: `角色状态已${status === 1 ? '启用' : '禁用'}`
    };
  }
};

export const roleApi = {
  // 获取角色列表（支持分页、搜索、筛选）
  async getRoles(params: GetRolesParams = {}): Promise<ApiResponse<Role[]>> {
    if (shouldUseMockServer()) {
      return mockRoleApi.getRoles(params);
    }
    try {
      const { page = 1, pageSize = 10, search, status } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (status !== undefined) queryParams.append('status', status.toString());
      
      const url = `${ROLE_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<RoleListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 如果后端返回的是标准格式
        const roleList = backendData.data as RoleListResponse;
        return {
          data: roleList.roles || [],
          total: roleList.total || 0,
          success: true,
          message: backendData.message || '获取角色列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取角色列表失败');
      }
    } catch (error) {
      console.error('获取角色列表失败:', error);
      
      // 如果后端API不可用，返回空数据（开发阶段）
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取角色列表失败'
      };
    }
  },

  // 创建角色
  async createRole(roleData: RoleFormData): Promise<ApiResponse<Role>> {
    if (shouldUseMockServer()) {
      return mockRoleApi.createRole(roleData);
    }
    try {
      // 发送POST请求
      const response = await http.post<BackendApiResponse<Role>>(ROLE_API_BASE, roleData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '角色创建成功'
        };
      } else {
        throw new Error(backendData.message || '创建角色失败');
      }
    } catch (error) {
      console.error('创建角色失败:', error);
      throw new Error(error instanceof Error ? error.message : '创建角色失败');
    }
  },

  // 更新角色
  async updateRole(roleId: number, roleData: Partial<RoleFormData>): Promise<ApiResponse<Role>> {
    if (shouldUseMockServer()) {
      return mockRoleApi.updateRole(roleId, roleData);
    }
    try {
      const url = `${ROLE_API_BASE}/${roleId}`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<Role>>(url, roleData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '角色信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新角色失败');
      }
    } catch (error) {
      console.error('更新角色失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新角色失败');
    }
  },

  // 删除角色
  async deleteRole(roleId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockRoleApi.deleteRole(roleId);
    }
    try {
      const url = `${ROLE_API_BASE}/${roleId}`;
      
      // 发送DELETE请求
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '角色删除成功'
        };
      } else {
        throw new Error(backendData.message || '删除角色失败');
      }
    } catch (error) {
      console.error('删除角色失败:', error);
      throw new Error(error instanceof Error ? error.message : '删除角色失败');
    }
  },

  // 切换角色状态
  async toggleRoleStatus(roleId: number, status: number): Promise<ApiResponse<Role>> {
    if (shouldUseMockServer()) {
      return mockRoleApi.toggleRoleStatus(roleId, status);
    }
    try {
      const url = `${ROLE_API_BASE}/${roleId}/status`;
      
      // 发送PATCH请求更新状态
      const response = await http.patch<BackendApiResponse<Role>>(url, { status });
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || `角色状态已${status === 1 ? '启用' : '禁用'}`
        };
      } else {
        throw new Error(backendData.message || '切换角色状态失败');
      }
    } catch (error) {
      console.error('切换角色状态失败:', error);
      throw new Error(error instanceof Error ? error.message : '切换角色状态失败');
    }
  }
};